package com.example.dao;

import com.example.controller.request.PeriodicalRequest;
import com.example.controller.request.PeriodicalsRequest;
import com.example.entity.Periodical;
import com.example.entity.Periodicals;
import io.micrometer.common.util.StringUtils;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;

public class PeriodicalsSpecification implements Specification<Periodicals> {

    private PeriodicalsRequest periodicalsRequest;

    public PeriodicalsSpecification(PeriodicalsRequest periodicalsRequest) {
        this.periodicalsRequest = periodicalsRequest;
    }

    @Override
    public Predicate toPredicate(Root<Periodicals> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        // name属性模糊匹配
        if (StringUtils.isNotEmpty(periodicalsRequest.getName())) {
            predicates.add(cb.like(root.get("name"), "%" + periodicalsRequest.getName() + "%"));
        }
        // periodical属性精确匹配
        if (StringUtils.isNotEmpty(periodicalsRequest.getPeriodical())) {
            predicates.add(cb.equal(root.get("periodical"), periodicalsRequest.getPeriodical()));
        }
        // 其他属性可以类似添加
        // ...

        // 使用and方法将所有的Predicate组合起来
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }

}
